// 定义ROI（替换为您的感兴趣区域）
var roi = ROI_Edge;

// 加载哨兵2号L2A数据
var sentinel2 = ee.ImageCollection('COPERNICUS/S2_SR_HARMONIZED')
  .filterDate('2022-08-01', '2022-08-31').filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 20))
  .filterBounds(roi);

// 定义去云函数
function maskS2clouds(image) {
  var qa = image.select('QA60');
  var cloudBitMask = 1 << 10;
  var cirrusBitMask = 1 << 11;
  var mask = qa.bitwiseAnd(cloudBitMask).eq(0)
      .and(qa.bitwiseAnd(cirrusBitMask).eq(0));
  return image.updateMask(mask);
}

// 应用去云处理
var cloudFreeSentinel2 = sentinel2.map(maskS2clouds);

// 计算遥感指数
var indices = cloudFreeSentinel2.map(function(image) {
  var ndvi = image.normalizedDifference(['B8A', 'B4']).rename('NDVI');
  var mndwi = image.normalizedDifference(['B3', 'B11']).rename('MNDWI');
  var lswi = image.normalizedDifference(['B8A', 'B11']).rename('LSWI');
  var ndsvi = image.normalizedDifference(['B8A', 'B2']).rename('NDSVI');
  var gcvi = image.expression('(B8A / B4) - 1', {
    'B8A': image.select('B8A'),
    'B4': image.select('B4')
  }).rename('GCVI');
  return image.addBands(ndvi).addBands(mndwi).addBands(lswi).addBands(ndsvi).addBands(gcvi);
});

// 合并波段与指数
var merged = indices.select(['B2', 'B4', 'B5', 'B6', 'B11', 'NDVI', 'MNDWI', 'LSWI', 'NDSVI', 'GCVI']);

// 上采样到10米分辨率
var resampled = merged.map(function(image) {
  return image.reproject({
    crs: 'EPSG:4326',
    scale: 10
  });
});

// 计算中值合成
var medianComposite = resampled.median();

// 统一数据类型为Float32
var float32Composite = medianComposite.toFloat();

// 导出为GeoTIFF
Export.image.toDrive({
  image: float32Composite,
  description: 'sentinel2_10m_median_float32',
  scale: 10,
  maxPixels: 1e13,
  region: roi,
  crs: 'EPSG:4326',
  fileFormat: 'GeoTIFF',
});

// 可视化NDVI
var ndviVis = {
  min: 0,
  max: 1,
  palette: ['FFFFFF', 'CE7E45', 'DF923D', '011D01', '011301']
};
Map.addLayer(float32Composite.select('NDVI'), ndviVis, 'NDVI Visualization');